package com.heima.search.interceptor;

import com.heima.utils.thread.UserThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Slf4j
public class AppTokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("【前置通知开始执行】");
        String userId = request.getHeader("userId");
        log.info("【前置拦截】:【获取userId为{}】",userId);
        if(userId != null){
            //存入到当前线程中
            UserThreadLocalUtil.setUser(Integer.parseInt(userId));
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("【拦截器结束执行】");
        //清理线程中的数据
        UserThreadLocalUtil.removeUser();
    }
}
